// net version of watcher, which can send filechange event to the subscriber via network.
'use strict';
const fs = require('fs');
const net = require('net');
const filename = process.argv[2];
function json(data){return JSON.stringify(data)+'\n';} 
let port=60030;
if (!filename){
    console.log(`Error: Please specify a filename!\nUsage:${process.argv[1]} filename [port|unix sock file]`);
    process.exit(-1);
}

// get the port argument 
if(process.argv.length>3){
    port = process.argv[3] ;
}

let conns = [];

let server = net.createServer(conn=>{
    const remote = conn.address().address

    console.log(`Subscriber ${remote} connected.`);
    conn.write(json({type:'watching',file:filename}));
    const watcher = fs.watch(
        filename,
        ()=>conn.write(json({type:'changed',timestamp:new Date()}))
    );
    conn.on('close',()=>{
        console.log(`Subscriber ${remote} disconnected.`);
        watcher.close();
    });
    conns.push(conn);
});
server.listen(port,()=>console.log(`Listening on ${port} for subscribers...`));
// on ctrl-c
process.on('SIGINT',()=>{
    console.log('now stoping...');
    // close every connection
    conns.forEach((con,index,arr)=>con.end());
    // then close server
    server.close(()=>console.log('Bye bye!'));
    // or it will be failed to start next time, if sock file exists.
    if(isNaN(port)){
        console.log("removing sock file.")
        fs.unlinkSync(port);
    }
});
